package com.xes.apps.ams.admin;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.xes.ams.client.api.BaseException;
import com.xes.ams.client.api.Result;
import com.xes.ams.client.api.ResultCode;

public class BaseController {
	private static final Logger log = LogManager.getLogger(BaseController.class);

	@ExceptionHandler(BaseException.class)
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Result<String> baseExceptionHandler(BaseException ex) {
		Result<String> result = new Result<>();
		if (ex instanceof BaseException) {
			result.setCode(ex.getResultCode().getCode());
			result.setMessage(ex.getResultCode().getMessage());
		} else {
			result.setCode(ResultCode.ERROR.getCode());
			result.setMessage(ResultCode.ERROR.getMessage());
			result.setData(ex.getMessage());
			log.error("发生系统错误{}", ex.getMessage(), ex);
		}
		return result;
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Result<String> handleAllException(Exception ex) {
		Result<String> result = new Result<>();
		result.setCode(ResultCode.ERROR.getCode());
		result.setMessage(ResultCode.ERROR.getMessage());
		result.setData(ex.getMessage());
		log.error("发生系统错误{}", ex.getMessage(), ex);
		return result;
	}
}
